<template>
	<view class="bg">
		<image class="bg-image" src="/static/rank-bg.png"></image>
		<view style="height: 350rpx;"></view>
		<uv-sticky bgColor="#fff">
			<uv-tabs :list="list" lineColor="#ff5000" @change="tabsChange"></uv-tabs>
		</uv-sticky>

		<view class="content" v-for="(item,index) in listData" :key="index">
			<view class="title">
				<view style="width: 30px;height: 30px;text-align: center;">
					<uni-icons v-if="index < 3" type="vip" size="30"
						:color="index==0?'#FFD700':index==1?'#C0C0C0':index==2?'#B87333':'#666'"></uni-icons>
					<view v-else>{{index+1}}</view>
				</view>
				<image class="avatar" :src="item.userInfo.avatarUrl"></image>
				<view class="title-text">{{item.userInfo.nickName}}</view>
			</view>
			<view
				:style="{'font-style':'italic','color':index==0?'#FFD700':index==1?'#C0C0C0':index==2?'#B87333':'#666'}">
				用时：{{formatTime(item[listKey])}}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'

	const list = [{
		name: '语文一年级',
		key: "chineseFirst"
	}, {
		name: '语文二年级',
		key: "chineseSecond"
	}, {
		name: '语文三年级',
		key: "chineseThird"
	}, {
		name: '语文四年级',
		key: "chineseFourth"
	}, {
		name: '语文五年级',
		key: "chineseFifth"
	}, {
		name: '数学一年级',
		key: "mathFirst"
	}, {
		name: '数学二年级',
		key: "mathSecond"
	}, {
		name: '数学三年级',
		key: "mathThird"
	}, {
		name: '数学四年级',
		key: "mathFourth"
	}, {
		name: '数学五年级',
		key: "mathFifth"
	}, {
		name: '英语一年级',
		key: "englishFirst"
	}, {
		name: '英语二年级',
		key: "englishSecond"
	}, {
		name: '英语三年级',
		key: "englishThird"
	}, {
		name: '英语四年级',
		key: "englishFourth"
	}, {
		name: '英语五年级',
		key: "englishFifth"
	}]
	const userInfo = ref()
	const listData = ref([])
	const listKey = ref('chineseFirst')
	onLoad(() => {
		try {
			const value = uni.getStorageSync("userInfo");
			if (value) {
				userInfo.value = value

				tabsChange(list[0])
			}
		} catch (e) {
			console.log(e)
		}
	})
	
	onShareAppMessage((res)=>{
		if (res.from === 'button') { // 来自页面内分享按钮
			console.log(res.target)
		}
		return {
			title: '挑战最快记录，等你来战！',
			path: '/pages/my/my/rank/rank'
		}
	})
	

	async function tabsChange(e) {
		listData.value = []
		// console.log('tabsChange',e)
		listKey.value = e.key

		const db = uniCloud.database();
		const dbCmd = db.command;
		const lbCollection = db.collection('leaderboard');
		const userCollection = db.collection('user');
		uni.showLoading({
			mask: true
		});
		// 1. 查询前100条数据（按指定字段降序）
		let lbResult = await lbCollection.where({
			[e.key]: dbCmd.exists(true)
		}).orderBy(e.key, 'asc').limit(100).get()

		// console.log('lbResult',lbResult)
		const topData = lbResult.result.data
		if (topData && topData.length > 0) {
			// 2. 提取所有用户ID
			const userIds = topData.map(item => item.userId).filter(id => id);
			if (userIds.length > 0) {
				// 3. 查询相应用户信息
				const userResult = await userCollection.where({
					_id: dbCmd.in(userIds)
				}).get();

				const userData = userResult.result.data
				// 4. 创建用户ID到用户信息的映射
				const userMap = {};
				userData.forEach(item => {
					userMap[item._id] = {
						nickName: item.nickName || '未知用户',
						avatarUrl: item.avatarUrl || '/static/my.png'
					};
				})

				// 5. 合并数据
				const resultWithUserInfo = topData.map(item => {
					return {
						...item,
						userInfo: userMap[item.userId] || {
							nickName: '未知用户',
							avatarUrl: '/static/my.png'
						}
					};
				});
				uni.hideLoading();
				// console.log('resultWithUserInfo',resultWithUserInfo)
				listData.value = resultWithUserInfo
			}
		} else {
			uni.hideLoading();
			listData.value = []
		}
	}

	// 格式化时间显示（将秒转换为分:秒格式）
	const formatTime = (seconds) => {
		const minutes = Math.floor(seconds / 60)
		const remainingSeconds = seconds % 60
		return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
	}
</script>

<style>
	@import 'rank.css'
</style>